﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Internal;
using Prism.Services.Dialogs;
using SmartPlant.Model;
using SmartPlant.Model.Biz;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;

namespace SmartPlant.Core.ViewModels
{
    public class NewInsViewModel : SmartDialogBase
    {
        public ObservableCollection<UnitTagConvention> UnitTagConventions { get; set; }
        public ObservableCollection<ComponentFunctionType> AllTypes { get; set; }

        private ComponentFunctionType _selectedType;
        public ComponentFunctionType selectedType
        {
            get { return _selectedType; }
            set
            {
                _selectedType = value;
                RaisePropertyChanged();
            }
        }
        private bool isBusy = true;
        public bool IsBusy
        {
            get { return isBusy; }
            set
            {
                isBusy = value;
                RaisePropertyChanged();
            }
        }
        private bool typeEnable;
        /// <summary>
        /// 下发列表能否用
        /// </summary>
        public bool TypeEnable
        {
            get { return typeEnable; }
            set
            {
                typeEnable = value;
                RaisePropertyChanged();
            }
        }

        public decimal _proId { get; set; }
        public decimal _unitId { get; set; }
        public decimal _loopId { get; set; }
        public IUnitTagConvService _unitTagConv { get; set; }

        private readonly IDialogService dialogService;
        private IInstrumentService _instrumentService;
        private decimal _copyfromId = 0;

        public NewInsViewModel(IDialogService dialogService, IUnitTagConvService unitTagConv, IInstrumentService instrumentService)
        {
            UnitTagConventions = new ObservableCollection<UnitTagConvention>();
            AllTypes = new ObservableCollection<ComponentFunctionType>();
            _proId = GlobalObject.CurrentProject.ProjId;
            this.dialogService = dialogService;
            _unitTagConv = unitTagConv;
            _instrumentService = instrumentService;
        }
        /// <summary>
        /// 确认按钮
        /// </summary>
        /// <param name="parameter"></param>
        public override async void ExecuteCloseDialogCommand(string parameter)
        {
            IsBusy = true;
            ButtonResult result = ButtonResult.None;
            DialogParameters parameters = new DialogParameters();
            if (parameter?.ToLower() == "true")
            {
                //ok按钮？ //除开最后一个必须要有值
                var emptyitem = UnitTagConventions.FirstOrDefault(p => p.IsReadOnly != true & p.Text.Length == 0);
                if (emptyitem != null)
                {
                    var tempTagConventions = UnitTagConventions.Where(p => p.separator != true).ToList();
                    int index = tempTagConventions.IndexOf(emptyitem) + 1;
                    if (index != tempTagConventions.Count)
                    {
                        dialogService.ShowMessage($"名称第{index}部分，未填写！");
                        IsBusy = false;
                        return;
                    }
                }
                string insName = string.Concat(
                    UnitTagConventions.Select(p =>
                    {
                        if (p.Text.Length > 0 & p.Text.Length < p.FuncParm2)
                        {
                            return p.Text.PadRight((int)p.FuncParm2, ' ');///补空格
                        }
                        return p.Text;
                    })
                );
                var lastSegmentSeparator = UnitTagConventions.Last(x => x.separator);
                if (insName.EndsWith(lastSegmentSeparator?.Text))
                {
                    insName = insName.Substring(0, insName.Length - lastSegmentSeparator.Text.Length);//后缀没有时，不需要带出最后那个分隔符号
                }
                decimal componentId = 0;
                var res = await _instrumentService.CreateInstrumentAsync(_proId, _unitId, _loopId, selectedType.CMPNT_FUNC_TYPE_ID, insName, _copyfromId);
                //这里需要加一个对创建错误、位号重复等的判断，而不要直接触发窗口的close要求
                if (res.statusCode == 200)
                {
                    if (decimal.TryParse(res.data, out componentId))
                    {

                        parameters.Add(DialogParameterKeys.Id, componentId);  //正常结果
                    }
                }
                else
                {
                    dialogService.ShowMessage(res.errors);//不正常结果，比如位号重复等。 
                    IsBusy = false;
                    return;
                }

                result = ButtonResult.Yes;
            }
            else if (parameter?.ToLower() == "false")
            {
                //取消按钮？
                result = ButtonResult.No;
            }
            RraiseRequestClose(new DialogResult(result, parameters));
            IsBusy = false;
        }

        public override async void OnDialogOpened(IDialogParameters parameters)
        {
            Title = parameters.GetValue<string>(DialogParameterKeys.Title);
            _copyfromId = parameters.GetValue<decimal>(DialogParameterKeys.Id);
            _unitId = parameters.GetValue<decimal>("unitId");
            _loopId = parameters.GetValue<decimal>("loopId");
            var x = await _unitTagConv.GetUnitTagConventionsAsync(_proId, _unitId, ObjectDefId.component);
            foreach (var item in x)
            {
                if (!string.IsNullOrEmpty(item.UnitPreffix))//前缀
                {
                    UnitTagConventions.Add(new UnitTagConvention() { Text = item.UnitPreffix, IsReadOnly = true, separator = true });
                }
                if (item.TAG_CONV_ATTR_REF == "PLANT_AREA_UNIT.UNIT_ID" && _unitId == GlobalObject.CurrentUnit.UnitId)
                {
                    //某一段是unit No，且刚好和要创建的那个unit为一个
                    item.Text = GlobalObject.CurrentUnit.UnitNum.ToString();
                }
                UnitTagConventions.Add(item);
            }
            var y = await _instrumentService.GetComponentFunctionTypes(_proId);
            AllTypes.AddRange(y);
            if (_copyfromId != 0)
            {
                //即复制
                TypeEnable = false;
                var sourceTag = await _instrumentService.GetInstrumentAsync(_proId, _copyfromId.ToString());
                selectedType = AllTypes.FirstOrDefault(x => x.CMPNT_FUNC_TYPE_ID == sourceTag.CMPNT_FUNC_TYPE_ID);
            }
            else
            {
                TypeEnable = true;
            }

            base.OnDialogOpened(parameters);
            IsBusy = false;
        }
    }
}
